package com.hqd.ch03.v34.web.servlet.mvc.method.annotation;

import com.hqd.ch03.v34.utils.StringUtils;
import com.hqd.ch03.v34.web.context.request.NativeWebRequest;
import com.hqd.ch03.v34.web.context.request.ServletWebRequest;
import com.hqd.ch03.v34.web.http.HttpHeaders;
import com.hqd.ch03.v34.web.method.HandlerMethod;
import com.hqd.ch03.v34.web.method.support.HandlerMethodReturnValueHandlerComposite;
import com.hqd.ch03.v34.web.servlet.mvc.method.InvocableHandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class ServletInvocableHandlerMethod extends InvocableHandlerMethod {

    private HandlerMethodReturnValueHandlerComposite returnValueHandlers;

    public ServletInvocableHandlerMethod(Object handler, Method method) {
        super(handler, method);
    }


    public ServletInvocableHandlerMethod(HandlerMethod handlerMethod) {
        super(handlerMethod);
    }


    public void setHandlerMethodReturnValueHandlers(HandlerMethodReturnValueHandlerComposite returnValueHandlers) {
        this.returnValueHandlers = returnValueHandlers;
    }


    public Object invokeAndHandle(ServletWebRequest webRequest,
                                  Object... providedArgs) throws Exception {

        Object returnValue = invokeForRequest(webRequest, providedArgs);

        if (returnValue == null) {
            if (isRequestNotModified(webRequest)) {
                disableContentCachingIfNecessary(webRequest);
                return null;
            }
        }

        /**
         * TODO：返回值处理
         */
//        this.returnValueHandlers.handleReturnValue(
//                returnValue, getReturnValueType(returnValue), webRequest);
        return returnValue;
    }

    public Object invokeForRequest(NativeWebRequest request,
                                   Object... providedArgs) throws Exception {

        Object[] args = getMethodArgumentValues(request, providedArgs);
        return doInvoke(args);
    }

    private boolean isRequestNotModified(ServletWebRequest webRequest) {
        return webRequest.isNotModified();
    }

    private void disableContentCachingIfNecessary(ServletWebRequest webRequest) {
        if (isRequestNotModified(webRequest)) {
            HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
            if (StringUtils.hasText(response.getHeader(HttpHeaders.ETAG))) {
                HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
            }
        }
    }
}
